
package main.nk.mygraph;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.util.mxConstants;
import com.mxgraph.view.mxGraph;
import com.mxgraph.view.mxStylesheet;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.embed.swing.SwingNode;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.CacheHint;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import main.nk.mygraph.pane.MyTabPane;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Hashtable;

public class Test1 extends Application {
    //root面板
    final BorderPane root = new BorderPane();

    mxGraphComponent component;

    //图形库面板
    StackPane pane = new StackPane();

    //画图的面板
    StackPane pane1 = new StackPane();


    mxGraph graph = new mxGraph();


    boolean flag = true;


    Object parent = graph.getDefaultParent();

    @Override
    public void start(Stage stage) throws InvocationTargetException, InterruptedException {
        Scene scene = new Scene(root, 900, 700);
        scene.getStylesheets().add(getClass().getResource("/application.css").toExternalForm());


        //创建菜单栏
        MenuBar menuBar = new MenuBar();


        Menu meun1 = new Menu("文件");
        Menu menu2 = new Menu("编辑");
        MenuItem item1 = new MenuItem("保存");
        item1.setMnemonicParsing(true);
        item1.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN));


        MenuItem item2 = new MenuItem("退出");
        item2.setMnemonicParsing(true);
        item2.setAccelerator(new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN));

        //退出编辑
        item2.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                Platform.exit();
                System.out.println("已退出");
            }
        });

        //保存操作
        item1.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                ObservableList<Node> children = pane1.getChildren();
                System.out.println(children);

                //如果pane1的子节点为空，则不保存
                if (!children.isEmpty()) {
                    //对画图面板进行一个截图
                    Image image = pane1.snapshot(null, null);

                    FileChooser fileChooser = new FileChooser();

                    //设置保存文件时的后缀
                    fileChooser.getExtensionFilters().addAll(
                            new FileChooser.ExtensionFilter("PNG", "*.png"),
                            new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                            new FileChooser.ExtensionFilter("BMP", "*.bmp"),
                            new FileChooser.ExtensionFilter("GIF", "*.gif")
                    );

                    fileChooser.setTitle("Save File");

                    //保存目录
                    File file = fileChooser.showSaveDialog(stage);
                    if(file!=null){
                        try {
                            //将图片保存到目标文件夹
                            ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
                            System.out.println("已保存");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }

            }
        });

        meun1.getItems().addAll(item1, item2);
        menuBar.getMenus().addAll(meun1, menu2);

        root.setTop(menuBar);
        //创建选项卡
        String[] tabName = {"基础图形"};
        MyTabPane tabPane = new MyTabPane(new TabPane(), 300, 200, tabName, true);
        TabPane tabPane1 = tabPane.getTabPane();


        //向选项卡中添加图片
        Image[] images = {new Image("images/rectangle.png"), new Image("images/event.png"),
                new Image("images/cloud.png"), new Image("images/actor.png"),
                new Image("images/hexagon.png"), new Image("images/cylinder.png"),
                new Image("images/rhombus.png"), new Image("images/triangle.png"),
                new Image("images/swimlane.png"), new Image("images/doubleellipse.png"),
                new Image("images/hline.png")};
        String[] userData = {"rectangle", "ellipse", "cloud", "actor",
                "hexagon", "cylinder", "rhombus", "triangle",
                "swimlane", "doubleEllipse", "line"};


        tabPane.addImage("基础图形", images, userData);


        ImageView[] imageView = tabPane.getImageView();

        for (ImageView view : imageView
        ) {
            view.setOnMouseClicked(new EventHandler<MouseEvent>() {
                public void handle(MouseEvent event) {
                    toCell((view.getUserData().toString()), stage);
                }
            });
        }

        component = new mxGraphComponent(graph);

        component.setDragEnabled(false);

        SwingNode node = new SwingNode();
        node.setContent(component);

       /* SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                node.setContent(component);
            }
        });*/

       /* new Timer().schedule(new TimerTask() {
            public void run() {
                node.getContent().repaint();
            }
        }, 100L);*/

      /*  SwingUtilities.invokeLater(() -> {
            node.setContent(component);
            node.requestFocus();
        });*/

        //添加监听器
        ChangeListener<Number>  sizeListener = new ChangeListener<Number>() {
            public void changed(ObservableValue<? extends Number> observableValue, Number number, Number t1) {
                node.setContent(component);
                System.gc();
            }
        };

        pane1.widthProperty().addListener(sizeListener);
        pane1.heightProperty().addListener(sizeListener);

        node.setCache(true);
        node.setCacheHint(CacheHint.SPEED);


        pane1.getChildren().add(node);

        pane.getChildren().addAll(tabPane1);
        root.setLeft(pane);
        root.setCenter(pane1);

        stage.setScene(scene);
        stage.show();

    }

    //画图的方法
    private void toCell(String userData, Stage stage) {
        System.out.println("点击了" + userData);
        //开启事务
        graph.getModel().beginUpdate();

        try {
            mxStylesheet stylesheet = new mxStylesheet();

            Hashtable<String, Object> style = new Hashtable<String, Object>();
            //设置文字的颜色
            style.put(mxConstants.STYLE_FONTCOLOR, "red");
            //设置图的背景颜色
            style.put(mxConstants.STYLE_FILLCOLOR, "white");
            //将样式添加到mxStylesheet中
            stylesheet.putCellStyle("style", style);
            graph.insertVertex(parent, null, userData, 100, 100, 100, 100, "shape=" + userData + ";style");
            graph.setStylesheet(stylesheet);

        } finally {
            graph.getModel().endUpdate();
        }

    }


    public static void main(String[] args) {
        launch(args);
    }

}

